package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.constant.Formats;
import io.xxx.xbutler.data.AddFriendRequestMapper;
import io.xxx.xbutler.data.RobotMapper;
import io.xxx.xbutler.domain.AddFriendRequest;
import io.xxx.xbutler.domain.Callback;
import io.xxx.xbutler.domain.GenderType;
import io.xxx.xbutler.domain.Robot;
import io.xxx.xbutler.sdk.TanJingClient;
import io.xxx.xbutler.sdk.request.AcceptNewFriendRequest;
import io.xxx.xbutler.sdk.response.AcceptNewFriendResponse;
import io.xxx.xbutler.service.RobotService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 新好友请求回调
 * <p>
 * 当机器人被用户加好友以后，我们会将这个申请添加好友的用户信息和请求回调给商家。便于之后选择是否添加该好友。
 * 如果对方是通过机器人的好友分享的名片来添加的机器人，
 * 则会在本回调中的vcFriendWxId、vcFriendSerialNo、vcFriendNickName三个参数中带对应机器人好友的参数值；
 * <pre>
 * {
 *     "nType": 3003,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "vcNewFriendWxId": "",
 *         "vcNewFriendSerialNo": "",
 *         "nSex": 1,
 *         "vcNickName": "",
 *         "vcBase64NickName": "",
 *         "vcWxAlias": "",
 *         "vcGexingQianming": "",
 *         "vcHeadImgUrl": "",
 *         "vcContent": "",
 *         "vcSource": "对方通过群聊添加",
 *         "vcChatRoomId": "",
 *         "vcChatRoomSerialNo": "",
 *         "vcFriendWxId": "",
 *         "vcFriendSerialNo": "",
 *         "vcFriendNickName": "",
 *         "dtCreateDate": ""
 *     }
 * }
 * </pre>
 */
@Slf4j
@Component
public class _3003Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private TanJingClient client;

    @Resource
    private AddFriendRequestMapper addFriendRequestMapper;

    @Resource
    private RobotMapper robotMapper;

    @Resource
    private RobotService robotService;

    @Override
    public String name() {
        return "新好友请求回调";
    }

    @Override
    public boolean supports(int type) {
        return type == 3003;
    }

    @Override
    public void handle(Callback callback) {
        String serialNo = callback.getRobotSerialNo();
        String robotId = callback.getRobotId();
        String robotSerialNo = callback.getRobotSerialNo();
        JSONObject data = (JSONObject) callback.getData();
        String newFriendId = data.getString("vcNewFriendWxId");
        String newFriendSerialNo = data.getString("vcNewFriendSerialNo");

        try {
            AddFriendRequest request = new AddFriendRequest()
                    .setId(idGenerator.next())
                    .setRobotId(robotId)
                    .setRobotSerialNo(robotSerialNo)
                    .setSerialNo(serialNo)
                    .setNewFriendId(newFriendId)
                    .setNewFriendSerialNo(newFriendSerialNo)
                    .setGender(GenderType.valueOf(data.getInteger("nSex")))
                    .setName(data.getString("vcNickName"))
                    .setBase64Name(data.getString("vcBase64NickName"))
                    .setAlias(data.getString("vcWxAlias"))
                    .setSignature(data.getString("vcGexingQianming"))
                    .setAvatar(data.getString("vcHeadImgUrl"))
                    .setContent(data.getString("vcContent"))
                    .setSource(data.getString("vcSource"))
                    .setRoomId(data.getString("vcChatRoomId"))
                    .setRoomSerialNo(data.getString("vcChatRoomSerialNo"))
                    .setFriendId(data.getString("vcFriendWxId"))
                    .setFriendSerialNo(data.getString("vcFriendSerialNo"))
                    .setFriendName(data.getString("vcFriendNickName"))
                    .setFriendTime(LocalDateTime.parse(data.getString("dtCreateDate"), Formats.DATETIME_FORMATTER));
            addFriendRequestMapper.insert(request);
        } catch (Exception e) {
            log.error("保存申请好友请求失败[serialNo:{}, robotId:{}, newFriendId:{}]", serialNo, robotId, newFriendId, e);
        }

        Robot robot = robotMapper.selectById(robotId);
        if (robot == null) {
            log.warn("机器人不存在[serialNo:{}, robotId:{}]", serialNo, robotId);
            return;
        }

        if (!robot.getAutoAddFriend()) {
            log.info("机器人不自动同意好友申请[serialNo:{}, robotId:{}]", serialNo, robotId);
            return;
        }

        AcceptNewFriendRequest acceptRequest = new AcceptNewFriendRequest()
                .setRobotSerialNo(robotSerialNo)
                .setSerialNo(serialNo);
        AcceptNewFriendResponse acceptResponse = client.execute(acceptRequest);
        if (acceptResponse.isSuccess()) {
            log.info("好友申请已同意[serialNo:{}, robotId:{}, newFriendId:{}]", serialNo, robotId, newFriendId);
            robotService.sendBind(robotId, robotSerialNo, newFriendSerialNo);   // 发送绑定卡片后需要老板点击
        } else {
            log.error("好友申请同意失败[serialNo:{}, robotId:{}, newFriendId:{}, response:{}]",
                    serialNo, robotId, newFriendId, JSON.toJSONString(acceptResponse));
        }
    }
}
